package com.compmov.socialnetwork;

import java.util.List;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Point;
import android.graphics.drawable.Drawable;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Toast;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;

public class SocialNetwork extends  MapActivity {
	
	double lat=19.51;
	double lon=-99.1291;

	private MapView mapView;
	private LocationManager lm;
	private LocationListener ll;
	private MapController mc;
	GeoPoint p = null;
	Drawable defaultMarker = null;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {		
		super.onCreate(savedInstanceState);
		setContentView(R.layout.show_map);		
	/*	MapView mapView = (MapView) findViewById(R.id.mapview);
		mapView.setBuiltInZoomControls(true);
		MapController mc = mapView.getController();		
		
		//Se agrega el geo pin al mapa
		MapOverlay mapOverlay = new MapOverlay();
		List<Overlay> listOfOverlays = mapView.getOverlays();
		listOfOverlays.clear();
		listOfOverlays.add(mapOverlay);
		
		lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
		ll = new MyLocationListener();
		lm.requestLocationUpdates(
				LocationManager.GPS_PROVIDER,
				0,
				0,
				ll);

		///Get the current location in start-up
		/*GeoPoint initGeoPoint = new GeoPoint(
				(int)(lm.getLastKnownLocation(
						LocationManager.GPS_PROVIDER)
						.getLatitude()*1000000),
						(int)(lm.getLastKnownLocation(
								LocationManager.GPS_PROVIDER)
								.getLongitude()*1000000));
	
		/*p = new GeoPoint(
				(int) (lat * 1E6),
				(int) (lon * 1E6));
		mc.animateTo(p);
		//mc.animateTo(initGeoPoint);*/
	}

	class MapOverlay extends Overlay {

		/**
		 * MEtodo que dibuja el mapa, se sobreescribe para poder agregar el geo pin
		 * a la imagen del mapa, este pin funcionara como marcador para la ubicacion
		 * señalada por el usuario
		 * @param canvas
		 * @param mapView   MapaView en el cual se añadira el pin
		 * @param shadow
		 * @param when
		 * @return
		 */
		@Override
		public boolean draw(Canvas canvas, MapView mapView,
				boolean shadow, long when) {
			super.draw(canvas, mapView, shadow);

			//Se obtiene la ubicacion del GeoPoint y se conviete en pixeles
			Point screenPts = new Point();
			mapView.getProjection().toPixels(p, screenPts);

			//Se agrega el marcador (GeoPin)
			Bitmap bmp = BitmapFactory.decodeResource(
					getResources(), R.drawable.geopin);
			canvas.drawBitmap(bmp, screenPts.x, screenPts.y - 48, null);
			return true;
		}

		/**
		 * Funcion que se llama cuando el mapa es tocado por el usuario
		 * @param event Evento a utilizar
		 * @param mapView   MapaView en el cual se inicio el evento
		 * @return
		 */
		@Override
		public boolean onTouchEvent(MotionEvent event, MapView mapView) {
			//Si se toco el mapa
			if (event.getAction() == 1) {
				//Se obtiene la ubicacion de donde se toco (X,Y)
				GeoPoint p = mapView.getProjection().fromPixels(
						(int) event.getX(),
						(int) event.getY());
				//Se convierten los puntos a Latitud y Longitud y se muestra un
				//mensaje en pantalla
				Toast.makeText(getBaseContext(),
						p.getLatitudeE6() / 1E6 + ","
						+ p.getLongitudeE6() / 1E6,
						Toast.LENGTH_SHORT).show();
			}
			return false;
		}
	}

	private class MyLocationListener implements LocationListener{
		public void onLocationChanged(Location argLocation) {
			// TODO Auto-generated method stub
			GeoPoint myGeoPoint = new GeoPoint(
					(int)(argLocation.getLatitude()*1000000),
					(int)(argLocation.getLongitude()*1000000));
			/*
			 * it will show a message on 
			 * location change
           Toast.makeText(getBaseContext(),
                   "New location latitude [" +argLocation.getLatitude() +
                   "] longitude [" + argLocation.getLongitude()+"]",
                   Toast.LENGTH_SHORT).show();
			 */

			mc.animateTo(myGeoPoint);
		}

		public void onProviderDisabled(String provider) {
			// TODO Auto-generated method stub
		}

		public void onProviderEnabled(String provider) {
			// TODO Auto-generated method stub
		}

		public void onStatusChanged(String provider,
				int status, Bundle extras) {
			// TODO Auto-generated method stub
		}
	}    


		@Override
		protected boolean isRouteDisplayed() {
			// TODO Auto-generated method stub
			return false;
		}

		public void showPerfil(View v){
			Intent nuevoIntent = new Intent(this.getApplicationContext(),
					Perfil.class);					
			startActivity(nuevoIntent);
		}
		
		@Override
		public boolean onCreateOptionsMenu(Menu menu) {
			MenuInflater inflater = getMenuInflater();
			inflater.inflate(R.menu.options_menu, menu);
			return true;
		}

		//  @Override
		public boolean onOptionsItemSelected(MenuItem item) {
			// Handle item selection
			Intent intent;
			switch (item.getItemId()) {
			case R.id.itmBuscar:
				 intent = new Intent(this.getApplicationContext(),Buscar.class);
				 startActivity(intent);   
				// startActivityForResult(intent,  RESULT_OK);
	                finish();
	                
				return true;
			case R.id.itmAgregar:
				Intent nuevoIntent = new Intent(getApplicationContext(), Agregar.class);
		  		startActivityForResult(nuevoIntent,0);		
		  		
				return true;
			case R.id.itmLogOut:
				  intent = new Intent(this.getApplicationContext(),Main.class);
	                startActivity(intent);
	                finish();
				return true;
			case R.id.itmExit:
				finish();
				return true;
			default:
				return super.onOptionsItemSelected(item);
			}
		}
		
		protected void onActivityResult(int requestCode, int resultCode,
	            Intent data) {

	  			if(resultCode==-1){
	  		  		/*Ejemplo de mandar los datos del buscar por extras*/
	  				
	  		  		int m=data.getIntExtra("hola", 0);
	  				Toast notificacionToast = Toast
	  				.makeText(getApplicationContext(),
	  						String.valueOf(resultCode)+","+m,
	  						Toast.LENGTH_SHORT);
	  		notificacionToast.show();
				}
	    
	    }

	}